package com.wclass.controller.app;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wclass.common.DateUtil;
import com.wclass.common.MD5Utils;
import com.wclass.common.ReturnObject;
import com.wclass.entity.*;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.model.UserMobile;
import com.wclass.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 张浩高
 * @since 2018-12-20
 */
@Api(description = "用户")
@RestController
@RequestMapping("/baseAppUser")
public class BaseAppUserController {

    /**
     * 融云
     */
    @Value("${rong.appKey}")
    private String appKey;
    /**
     * 融云
     */
    @Value("${rong.appSecret}")
    private String appSecret;


    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private IBaseOrganService iBaseOrganService;
    @Autowired
    private IBaseFocusService iBaseFocusService;
    @Autowired
    private ICourseInfoService iCourseInfoService;
    @Autowired
    private ICouresOrderService iCouresOrderService;
    @Autowired
    private ICouresProgressBillService iCouresProgressBillService;
    @Autowired
    private IUserStatisticsBillService iUserStatisticsBillService;
    @Autowired
    private IBaseUserSettingService iBaseUserSettingService;

    @ApiOperation("获取用户勋章，platform为平台推荐，person为个人认证，organ为机构认证，0：无勋章，1：有勋章")
    @RequestMapping(value = "/getMeadalCount", method = RequestMethod.POST)
    public ReturnObject<Map<String, Object>> getMeadalCount(){
        Map<String, Object> map = Maps.newHashMap();
        map.put("platform", 0);
        map.put("person", 0);
        map.put("organ", 0);

        // 平台推荐
        BaseAppUser user = iBaseAppUserService.selectOneById(BaseContextHandler.getUserID());
        map.put("platform", user.getPlatform());

        //个人认证
        if (user.getAuditStatus() == 0)
            map.put("person", 1);

        //机构认证
        EntityWrapper<BaseOrgan> organEw = new EntityWrapper<>();
        organEw.eq("user_id", BaseContextHandler.getUserID());
        organEw.eq("audit_status", 1);
        BaseOrgan organ = iBaseOrganService.selectOne(organEw);
        if (organ != null)
            map.put("organ", 1);

        return new ReturnObject<>(0, "获取成功", map);
    }

    @ApiOperation("老师端-数据统计")
    @RequestMapping(value = "/getStatisticsInfoByUserId", method = RequestMethod.POST)
    public ReturnObject<Object> getStatisticsInfoByUserId(@ApiParam("类型 1 日 2 周 3 月") @RequestParam(defaultValue = "1") Integer type) {
        Map<String, Object> map = Maps.newHashMap();
        ArrayList clickNum = new ArrayList();
        ArrayList clickTime = new ArrayList();
        ArrayList makeNum = new ArrayList();
        ArrayList makeTime = new ArrayList();
        ArrayList moneyAmount = new ArrayList();
        ArrayList moneyTime = new ArrayList();

        EntityWrapper<UserStatisticsBill> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID()).eq("type", type);
        ew.orderBy("crt_time", true);
        List<UserStatisticsBill> list = iUserStatisticsBillService.selectList(ew);

        for (int i = 0;i < list.size();i++) {
            UserStatisticsBill userStatisticsBill = list.get(i);
            clickNum.add(userStatisticsBill.getClickNum());
            makeNum.add(userStatisticsBill.getOrderNum());
            moneyAmount.add(userStatisticsBill.getOrderAmount());

            String time = DateUtil.format(userStatisticsBill.getCrtTime(), "MM-dd");
            clickTime.add(time);
            makeTime.add(time);
            moneyTime.add(time);
        }
        map.put("clickNum", clickNum);
        map.put("clickTime", clickTime);
        map.put("makeNum", makeNum);
        map.put("makeTime", makeTime);
        map.put("moneyAmount", moneyAmount);
        map.put("moneyTime", moneyTime);

        return new ReturnObject<>(0, "获取成功", map);
    }

    @ApiOperation("获取用户排行榜")
    @RequestMapping(value = "/getRankingPage", method = RequestMethod.POST)
    public ReturnObject<List<BaseAppUser>> getRankingPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer limit,
                                                          @ApiParam("页数") @RequestParam(defaultValue = "1") Integer offset) {
        EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
        ew.orderBy("all_amount", false);
        Page<BaseAppUser> obj = iBaseAppUserService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取个人信息")
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public ReturnObject<UserMobile> info() {
        try {
            UserMobile userMobile = new UserMobile();
            BaseAppUser baseAppUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            baseAppUser.setPassword(null);
            BeanUtils.copyProperties(baseAppUser, userMobile);
            if (baseAppUser.getInstitutionId() != null) {
                userMobile.setInstitution(iBaseOrganService.selectById(baseAppUser.getInstitutionId()).getName());
            }
            if (baseAppUser.getAuditStatus() < 3)
                userMobile.setAuditType(0);
            if (baseAppUser.getInstitutionId() != null) {
                BaseOrgan organ = iBaseOrganService.selectOne(new EntityWrapper<BaseOrgan>().eq("user_id", baseAppUser.getId()).eq("id", baseAppUser.getInstitutionId()));
                if (organ != null) {
                    userMobile.setAuditType(1);
                    userMobile.setOrganType(organ.getType());
                    userMobile.setInstitutionAuditState(organ.getAuditStatus());
                }
            }

            return new ReturnObject<>(0, "请求成功", userMobile);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }

    @ApiOperation("获取同一机构下的老师")
    @RequestMapping(value = "/getColleague", method = RequestMethod.POST)
    public ReturnObject<List<UserMobile>> getColleague() {
        List<UserMobile> list = Lists.newArrayList();
        BaseAppUser baseAppUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
        if (baseAppUser.getInstitutionId() == null) {
            UserMobile userMobile = new UserMobile();
            baseAppUser.setPassword(null);
            BeanUtils.copyProperties(baseAppUser, userMobile);
            list.add(userMobile);
        } else {
            List<BaseAppUser> userList = iBaseAppUserService.selectList(
                    new EntityWrapper<BaseAppUser>().eq("institution_id", baseAppUser.getInstitutionId()).eq("institution_invite_state", 2));
            for (BaseAppUser appuser : userList) {
                UserMobile userMobile = new UserMobile();
                appuser.setPassword(null);
                BeanUtils.copyProperties(appuser, userMobile);
                list.add(userMobile);
            }
        }
        return new ReturnObject<>(0, "请求成功", list);

    }

    @ApiOperation("修改个人信息")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ReturnObject<BaseAppUser> edit(@ApiParam("昵称") String nickname,
                                          @ApiParam("密码") String password,
                                          @ApiParam("真实姓名") String username,
                                          @ApiParam("职位") String postname,
                                          @ApiParam("教学成果") String teachingAchieve,
                                          @ApiParam("个人展示") String selfShow,
                                          @ApiParam("性别 1 男 2 女") Integer sex,
                                          @ApiParam("收货地址") String address,
                                          @ApiParam("收货人") String receiver,
                                          @ApiParam("收货人手机号") String receiverPhone,
                                          @ApiParam("省") String province,
                                          @ApiParam("市") String city,
                                          @ApiParam("区") String area,
                                          @ApiParam("手机号码") String phone,
                                          @ApiParam("头像") String pictureAddress,
                                          @ApiParam("关注品类json串") String courseType,
                                          @ApiParam("微信openid") String weixin,
                                          @ApiParam("邮箱") String mail,
                                          @ApiParam("个人介绍") String personalIntro) {
        try {
            BaseAppUser userVo = iBaseAppUserService.selectById(BaseContextHandler.getUserID());

            if (StringUtils.isNotBlank(username)) {
                userVo.setRealName(username);
            }
            if (StringUtils.isNotBlank(postname)) {
                userVo.setPostname(postname);
            }
            if (StringUtils.isNotBlank(teachingAchieve)) {
                userVo.setTeachingAchieve(teachingAchieve);
            }
            if (StringUtils.isNotBlank(selfShow)) {
                userVo.setSelfShow(selfShow);
            }
            if (StringUtils.isNotBlank(weixin)) {
                userVo.setWeixin(weixin);
            }
            if (StringUtils.isNotBlank(nickname)) {
                userVo.setNickName(nickname);
            }

            if (StringUtils.isNotBlank(password)) {
                userVo.setPassword(MD5Utils.encode2hex(password));
            }

            if (StringUtils.isNotBlank(phone)) {
                userVo.setPhone(phone);
            }

            if (StringUtils.isNotBlank(pictureAddress)) {
                userVo.setPictureAddress(pictureAddress);
            }

            if (StringUtils.isNotBlank(province)) {
                userVo.setProvince(province);
            }

            if (StringUtils.isNotBlank(city)) {
                userVo.setCity(city);
            }

            if (StringUtils.isNotBlank(mail)) {
                userVo.setMail(mail);
            }

            if (StringUtils.isNotBlank(area)) {
                userVo.setArea(area);
            }

            if (StringUtils.isNotBlank(address)) {
                userVo.setFamilyAddress(address);
            }

            if (StringUtils.isNotBlank(receiver)) {
                userVo.setReceiver(receiver);
            }

            if (StringUtils.isNotBlank(receiverPhone)) {
                userVo.setReceiverPhone(receiverPhone);
            }

            if (sex != null) {
                userVo.setSex(sex);
            }

            if (StringUtils.isNotBlank(courseType)) {
                userVo.setCourseType(courseType);
            }

            if (StringUtils.isNotBlank(personalIntro)) {
                userVo.setPersonalIntro(personalIntro);
            }
            iBaseAppUserService.updateById(userVo);

            return new ReturnObject<>(0, "修改成功", userVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }

    @ApiOperation("个人入驻-申请")
    @RequestMapping(value = "/auditEdit", method = RequestMethod.POST)
    public ReturnObject auditEdit(@ApiParam("教学领域（json存储）") String teachingField,
                                  @ApiParam("头像") String pictureAddress,
                                  @ApiParam("真实姓名") String username,
                                  @ApiParam("证件类型：0：身份证 1：军官证 2：护照 3：驾驶证 （目前只考虑身份证）") Integer idCardType,
                                  @ApiParam("证件号码") String idCardNo,
                                  @ApiParam("证件照片地址") String idCardPhoto,
                                  @ApiParam("邮箱") String mail,
                                  @ApiParam("个人简介") String personalIntro) {
        try {
            BaseAppUser baseAppUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            baseAppUser.setTeachingField(teachingField);
            baseAppUser.setPictureAddress(pictureAddress);
            baseAppUser.setRealName(username);
            baseAppUser.setIdCardType(idCardType);
            baseAppUser.setIdCardNo(idCardNo);
            baseAppUser.setIdCardPhoto(idCardPhoto);
            baseAppUser.setMail(mail);
            baseAppUser.setAuditStatus(2);
            baseAppUser.setPersonalIntro(personalIntro);
            iBaseAppUserService.updateById(baseAppUser);
            return new ReturnObject(0, "请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @ApiOperation("解除微信绑定")
    @RequestMapping(value = "/boundWeixin", method = RequestMethod.POST)
    public ReturnObject boundWeixin() {
        try {
            BaseAppUser baseAppUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            baseAppUser.setWeixin("");
            iBaseAppUserService.updateById(baseAppUser);
            return new ReturnObject(0, "解绑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @ApiOperation("解除邮箱绑定")
    @RequestMapping(value = "/boundEmail", method = RequestMethod.POST)
    public ReturnObject boundEmail() {
        try {
            BaseAppUser baseAppUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            baseAppUser.setMail("");
            iBaseAppUserService.updateById(baseAppUser);
            return new ReturnObject(0, "解绑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @IgnoreAuth
    @ApiOperation("获取指定用户主页信息")
    @RequestMapping(value = "/getTeacherInfo", method = RequestMethod.POST)
    public ReturnObject getUserInfo(@ApiParam("查看对象id") Long userId,
                                    @ApiParam("当前登录用户id") Long localUserId) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            BaseAppUser baseAppUser = iBaseAppUserService.selectById(userId);
            UserMobile userMobile = new UserMobile();
            baseAppUser.setPassword(null);
            BeanUtils.copyProperties(baseAppUser, userMobile);
            if (userMobile.getInstitutionId() != null) {
                BaseOrgan organ = iBaseOrganService.selectById(userMobile.getInstitutionId());
                if (organ.getType() == 1) {
                    userMobile.setInstitution(organ.getName());
                } else {
                    userMobile.setInstitution(userMobile.getNickName() + "教师团队");
                }
            }
            userMobile.setFocusUser(iBaseFocusService.selectCount(new EntityWrapper<BaseFocus>().eq("user_id",
                    localUserId).eq("focus_user_id", userId)) == 0 ? 0 : 1);
            map.put("userInfo", userMobile);//老师的个人信息对象
            return new ReturnObject(0, "获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @ApiOperation("我的-个人认证中心-获取基本信息")
    @RequestMapping(value = "/getAuthenticationInfo", method = RequestMethod.POST)
    public ReturnObject<Object> getAuthenticationInfo(){
        BaseAppUser appUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());

        Map<String, Object> map = Maps.newHashMap();
        map.put("realName", appUser.getRealName());
        map.put("idCardNo", appUser.getIdCardNo());
        map.put("auditTime", appUser.getAuditTime());
        map.put("teachingCase", appUser.getTeachingCase());
        map.put("aptitude", appUser.getAptitude());
        map.put("teachingAchieve", appUser.getTeachingAchieve());
        map.put("sina", appUser.getSina());
        map.put("weixin", appUser.getWeixin());
        map.put("terrace", appUser.getTerrace());
        return new ReturnObject<>(0, "", map);
    }

    @ApiOperation("我的-个人认证中心-新增编辑提交")
    @RequestMapping(value = "/authenticationCenter", method = RequestMethod.POST)
    public ReturnObject authenticationCenter(@ApiParam("授课案例") String teachingCase,
                                             @ApiParam("资讯证明") String aptitude,
                                             @ApiParam("教学成果") String teachingAchieve,
                                             @ApiParam("新浪微博") String sina,
                                             @ApiParam("微信公众号") String weixin,
                                             @ApiParam("其他平台") String terrace) {
        try {
            BaseAppUser appUser = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            appUser.setIdCardType(0);
            if (appUser.getAuditTime() == null)
                appUser.setAuditTime(new Date());
            appUser.setAuditStatus(2);
            appUser.setTeachingCase(teachingCase);
            appUser.setAptitude(aptitude);
            appUser.setTeachingAchieve(teachingAchieve);
            appUser.setSina(sina);
            appUser.setWeixin(weixin);
            appUser.setTerrace(terrace);
            iBaseAppUserService.updateById(appUser);

            return new ReturnObject(0, "认证已提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @ApiOperation("教师-获取学生列表")
    @RequestMapping(value = "/getStudentList", method = RequestMethod.POST)
    public ReturnObject<List<BaseAppUser>> getStudentList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer limit,
                                                          @ApiParam("页数") @RequestParam(defaultValue = "1") Integer offset,
                                                          @ApiParam("教师id，不传默认为自己的id") Long userId) {
        if (userId == null)
            userId = BaseContextHandler.getUserID();
        Page<Long> obj = iCouresOrderService.selectTeaStudentList(new Page<>(offset, limit), userId);
        List<BaseAppUser> list = Lists.newArrayList();
        for (Long payPersonId : obj.getRecords()) {
            BaseAppUser appUser = iBaseAppUserService.selectById(payPersonId);
            appUser.setPassword(null);
            list.add(appUser);
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), list);
    }

    @ApiOperation("获取用户隐私、接受、通知设置")
    @RequestMapping(value = "/getUserSetting", method = RequestMethod.POST)
    public ReturnObject<BaseUserSetting> getUserSetting(@ApiParam("获取类型，1：隐私设置，2：接收信息设置，3：通知设置") @RequestParam Integer type){
        BaseUserSetting userSetting = iBaseUserSettingService.selectOne(
                new EntityWrapper<BaseUserSetting>().eq("user_id", BaseContextHandler.getUserID()).eq("type", type));

        return new ReturnObject(0, "获取成功", userSetting);
    }

    @ApiOperation("保存用户隐私、接受、通知设置")
    @RequestMapping(value = "/saveUserSetting", method = RequestMethod.POST)
    public ReturnObject saveUserSetting(@ApiParam("id") Long id,
                                        @ApiParam("获取类型，1：隐私设置，2：接收信息设置，3：通知设置") @RequestParam Integer type,
                                        @ApiParam("接收、查看范围，1：所有人可见，2：关注我的人可见，3：我的粉丝可见，4：仅自己可见") Integer range,
                                        @ApiParam("点赞权限，1：所有人，2：我关注的人，3：我的粉丝，4：任何人不允许") Integer likeAuth,
                                        @ApiParam("评论权限，1：所有人，2：我关注的人，3：我的粉丝，4：任何人不允许") Integer replyAuth,
                                        @ApiParam("允许陌生人查看关注的人，0：否，1：是") Integer viewFocus,
                                        @ApiParam("允许陌生人查看我的粉丝，0：否，1：是") Integer viewFans,
                                        @ApiParam("开启上课提醒，0：否，1：是") Integer classRemind){
        BaseUserSetting userSetting;
        if (id == null) {
            userSetting = new BaseUserSetting();
            userSetting.setCrtTime(new Date());
            userSetting.setUserId(BaseContextHandler.getUserID());
            userSetting.setType(type);
            userSetting.setRange(range);
            userSetting.setLikeAuth(likeAuth);
            userSetting.setReplyAuth(replyAuth);
            userSetting.setViewFocus(viewFocus);
            userSetting.setViewFans(viewFans);
            userSetting.setClassRemind(classRemind);
            iBaseUserSettingService.insert(userSetting);
        } else {
            userSetting = iBaseUserSettingService.selectById(id);
            userSetting.setRange(range);
            userSetting.setLikeAuth(likeAuth);
            userSetting.setReplyAuth(replyAuth);
            userSetting.setViewFocus(viewFocus);
            userSetting.setViewFans(viewFans);
            userSetting.setClassRemind(classRemind);
            iBaseUserSettingService.updateById(userSetting);
        }
        return new ReturnObject(0, "操作成功");
    }

}

